import ErrorMessage from '@/constants/ErrorMessage';
import HTTP_STATUS from '../enums/HTTP_STATUS';
import RequestOptions = UniNamespace.RequestOptions

export default {
  baseOptions(params, method: 'GET' | 'POST') {
    const { url, data } = params;
    let headerConfig: any = {};
    let contentType = 'application/json';
    try {
      const { token } = uni.getStorageSync('USER_INFO');
      contentType = params.contentType || contentType;
      headerConfig = {
        'content-type': contentType,
        authorization: token,
      };
      if (token === undefined || token === '') {
        headerConfig = {
          'content-type': contentType,
        };
      }
    } catch (error) {
      headerConfig = {
        'content-type': contentType,
      };
    }
    const option: RequestOptions = {
      url,
      data,
      method,
      header: headerConfig,
      success(res) {
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          return uni.showToast({
            icon: 'error',
            title: ErrorMessage[HTTP_STATUS.NOT_FOUND],
            duration: 2000,
          });
        }
        if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          return uni.showToast({
            icon: 'error',
            title: ErrorMessage[HTTP_STATUS.BAD_GATEWAY],
            duration: 2000,
          });
        }
        if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          return uni.showToast({
            icon: 'error',
            title: ErrorMessage[HTTP_STATUS.FORBIDDEN],
            duration: 2000,
          });
        }
        if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data;
        }
        if (res.statusCode === HTTP_STATUS.SERVER_ERROR) {
          return uni.showToast({
            icon: 'error',
            title: ErrorMessage[HTTP_STATUS.SERVER_ERROR],
            duration: 2000,
          });
        }
        return uni.showToast({
          icon: 'error',
          title: '未知错误请联系管理员',
          duration: 2000,
        });
      },
      fail() {
        uni.showToast({
          icon: 'error',
          title: '请求接口出现问题',
          duration: 2000,
        });
      },
    };
    return new Promise((resolve) => {
      // 重新获取用户信息
      if (!uni.getStorageSync('USER_INFO')) {
        uni.login().then((res) => {
          console.log(res);
        });
      }
      uni.request({ ...option }).then((res) => {
        console.log(res);
        resolve(res);
      });
    });
  },
  get(url, data) {
    const params = { url, data };
    return this.baseOptions(params, 'GET');
  },
  post(url, data, contentType) {
    const params = { url, data, contentType };
    return this.baseOptions(params, 'POST');
  },
};
